import { createRouter, createWebHistory, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import Layout from '@/views/Layout/index.vue'
import asyncRouter from './permission'
import { hasPermission } from '@/utils/common/permissionAuth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { component } from 'v-viewer'
NProgress.configure({
  showSpinner: false
})
const routes = [
  {
    path: '/',
    redirect: '/login',
    hidden: true
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/index.vue'),
    hidden: true,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/Register/index.vue'),
    hidden: true,
    meta: {
      title: '企业注册'
    }
  },

  // 首页
  {
    path: '/home',
    name: 'home',
    component: Layout,
    redirect: '/home/index',
    meta: {
      title: '首页',
      icon: 'HomeFilled'
    },
    children: [
      {
        path: 'index',
        meta: {
          title: '首页',
          icon: 'HomeFilled'
        },
        component: () => import('@/views/home/index.vue')
      }
    ]
  },
  {
    path: '/map',
    name: 'map',
    component: Layout,
    meta: {
      title: '地图',
      icon: ''
    },
    component: () => import('@/views/Map/index.vue'),
    hidden: true
  },
  {
    path: '/enterDetail',
    name: 'enterDetail',
    component: Layout,
    meta: {
      title: '企业详情',
      icon: ''
    },
    component: () => import('@/views/Enterprise/enterDetaile.vue'),
    hidden: true
  },
  {
    path: '/forgetPassword',
    name: 'forgetPassword',
    component: () => import('@/views/Personal/forgetPassword.vue'),
    hidden: true
  }
]
const cachAlll = {
  path: '/:cachAlll(.*)',
  component: () => import('@/components/common/404.vue'),
  hidden: true
}
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

const whiteList = ['/login', '/register', '/forgetPassword']

export async function initRouter() {
  const userStore = useUserStore()
  try {
    userStore.getUserInfo()
  } catch (error) {
    console.log(error)
  }

  // 清除所有动态添加的路由
  router.getRoutes().forEach((route) => {
    if (route.name && !routes.find((r) => r.name === route.name)) {
      router.removeRoute(route.name)
    }
  })

  let filterRouter = hasPermission(asyncRouter, userStore.userInfo.permission)
  filterRouter.push(cachAlll)
  // console.log('User college:', userStore.userInfo.college);
  // console.log('Filtered router before college check:', filterRouter);

  console.log(userStore.userInfo.college)
  if ((userStore.userInfo.identity = '管理员' && userStore.userInfo.college !== '*')) {
    // 修改过滤逻辑，只过滤掉 isAdmin: true 的子路由
    filterRouter = filterRouter.map((route) => {
      if (route.children) {
        return {
          ...route,
          children: route.children.filter((child) => !child.meta?.isAdmin)
        }
      }
      return route
    })
  }

  // console.log('Filtered router after college check:', filterRouter);
  // 添加动态路由
  filterRouter.forEach((item) => {
    router.addRoute(item)
  })

  userStore.permissionRouter = [...routes, ...filterRouter]
}

router.beforeEach(async (to, from) => {
  // console.log('路由拦截', to, from)
  // console.log(to)

  NProgress.start()
  const userStore = useUserStore()
  const token = userStore.token

  // 1.在白名单
  if (whiteList.includes(to.path)) {
    return true
  }
  // console.log(userStore.token)

  // 2.不在白名单且没有token
  if (!token) {
    return '/login'
  }

  // 3.有token
  try {
    // 3.1.判断有没有用户信息
    if (JSON.stringify(userStore.userInfo) === '{}') {
      // 获取用户信息
      await userStore.getUserInfo()
    }

    // 3.2.判断有没有权限路由
    if (userStore.permissionRouter.length === 0) {
      await initRouter()
      // 添加完动态路由后，需要重新进入当前路由
      return to.fullPath
    }

    return true
  } catch (error) {
    console.error('Route error:', error)
    userStore.clearUserInfo()
    return '/login'
  }
})

router.afterEach((to) => {
  // 修改标题
  document.title = `${to.meta.title + '-' || ''}实习就业管理系统`
  // 路由切换完毕后关闭
  NProgress.done()
})

export default router
